﻿using System;
using System.Web;
using System.Web.Security;

namespace rpxlogindemo.handlers.login
{
    /// <summary>
    /// Summary description for Rpx_Token_Handler
    /// </summary>
    public class RpxTokenHandler : IHttpHandler
    {
        private static void HandleLoginSuccess(HttpContext context)
        {
            string token = RpxTokenHandler.ExtractToken(context);
            var auth_info = rpxnow_library.rpxnowapi.requests.ApiFactory.Create().auth_info(token);
            if (auth_info.hasError)
                throw new Exception(auth_info.err.msg);

            var mu = Membership.GetUser((object)auth_info.profile.identifier);
            if (mu == null)
            {
                //   new user!
                MembershipCreateStatus s;
                mu = ((rpxnow_library.membership.OpenIdMembershipProvider)Membership.Provider).CreateUser(auth_info.profile.identifier,
                                                                                                            auth_info.profile.providerName,
                                                                                                            auth_info.profile.displayName,
                                                                                                            auth_info.profile.name.formatted,
                                                                                                            auth_info.profile.email,
                                                                                                            auth_info.profile.url,
                                                                                                            auth_info.profile.photo,
                                                                                                            out s);
            }
            FormsAuthentication.RedirectFromLoginPage(mu.UserName, false);
        }

        private static void RedirectBackToLoginPage(HttpContext context)
        {
            RpxTokenHandler.RedirectBackToLoginPage(context, string.Empty);
        }

        private static void RedirectBackToLoginPage(HttpContext context, string errorMessage)
        {
            string loginUrl = FormsAuthentication.LoginUrl + "?failed=true";

            if (!string.IsNullOrEmpty(context.Request.Form["returnUrl"]))
                loginUrl += string.Format("&returnUrl={0}", context.Request.Form["returnUrl"]);

            if (!string.IsNullOrEmpty(context.Request.Form["errorMessage"]))
                loginUrl += string.Format("&errorMessage={0}", context.Server.UrlEncode(errorMessage));

            context.Response.Redirect(loginUrl);
        }

        private static string ExtractToken(HttpContext context)
        {
            return context.Request.Form["token"];
        }

        private static bool HasToken(HttpContext context)
        {
            return !string.IsNullOrEmpty(context.Request.Form["token"]);
        }

        #region IHttpHandler Members

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            try
            {
                if (RpxTokenHandler.HasToken(context))
                    RpxTokenHandler.HandleLoginSuccess(context);
                else
                    RpxTokenHandler.RedirectBackToLoginPage(context);
            }
            catch (Exception ex)
            {
                RpxTokenHandler.RedirectBackToLoginPage(context, ex.Message);
            }
        }

        bool IHttpHandler.IsReusable
        {
            get { return false; }
        }

        #endregion
    }

}